#!/bin/bash

echo "Running pre-commit checks on your code..."

# 匹配.go文件
STAGED_GO_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep ".go$")

if [[ "$STAGED_GO_FILES" = "" ]]; then
    echo -e "\033[32mNo go files to update\033[0m"
    exit 0
fi

echo "Check golangci-lint is installed"
if !(golangci-lint --version 1>/dev/null); then
    echo "Installing golangci-lint..." && curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin v1.43.0
    if [[ $? -ne 0 ]]; then
        echo -e "\033[31mFailed to install golangci-lint\033[0m"
        exit 1
    fi
else
    echo "Lint is installed"
fi

PASS=true

echo "Lint go files..."
for FILE in $STAGED_GO_FILES
do
    # goimports会格式化代码并调整导入语句
    # 这里需要注意linux、windows的换行符问题CR/LF vs LF
    # gofmt默认使用\n作为换行符，windows下编辑文件默认为\r\n
    UNFORMATTED=$(goimports -l $FILE)
    if [[ "$UNFORMATTED" != "" ]];then
        goimports -w $PWD/$UNFORMATTED
        if [[ $? != 0 ]]; then
            PASS=false
        fi
    fi
    # goimports可能会对文件作出改动
    # 所以此处将更改提交至暂存区
    git add $FILE

    # golangci-lint检查
    if !(golangci-lint run $FILE); then
        PASS=false
        echo -e "\033[31mLint failed\033[0m"
        exit 1
    fi
done

if ! $PASS; then
    printf "\033[31mCode irregular, please check!\033[0m\n"
    exit 1
else
    printf "\033[32mPre-commit checks passed\033[0m\n"
fi

exit 0
